import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


export class Crisis {
  constructor(
    public id: number,
    public name: string
  ) {}
}

const CRISES = [
  new Crisis(1, '师傅被妖怪抓走了'),
  new Crisis(2, '大师兄被妖怪抓走了'),
  new Crisis(3, '二师兄被妖怪抓走了'),
  new Crisis(4, '沙师弟妖怪抓走了'),
];


@Injectable()
export class CrisisService {
  static nextCrisisId = 100;
  private crises$: BehaviorSubject<Crisis[]> = new BehaviorSubject<Crisis[]>(CRISES);

  getCrises() {
    return this.crises$;
  }

  getCrisis(id: number | string) {
    return this.getCrises().pipe(
      map(crises => crises.find(crisis => crisis.id === +id))
    );
  }

  addCrisis(name: string) {
    name = name.trim();
    if (name) {
      const crisis = new Crisis(CrisisService.nextCrisisId++, name);
      CRISES.push(crisis);
      this.crises$.next(CRISES);
    }
  }
}
